package com.authority.framework.log.manager.factory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;

import com.authority.framework.online.OnlineSession;
import com.authority.framework.web.domain.SysUserOnlineEntity;
import com.authority.framework.web.domain.SysLoginInForEntity;
import com.authority.framework.web.service.SysLoginInForService;
import com.authority.framework.web.service.SysUserOnlineService;
import com.authority.framework.base.util.DateUtils;
import com.authority.framework.base.util.ServletUtils;
import com.authority.framework.base.util.ShiroUtils;
import com.authority.framework.base.util.SpringUtils;
import com.authority.framework.base.util.address.AddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 异步工厂（产生任务用）
 * 
 * @author Mr.Yan
 *
 */
public class AsyncFactory
{
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 同步session到数据库
     *
     * @param session 在线用户会话
     * @return 任务task
     */
    public static TimerTask syncSessionToDb(final OnlineSession session)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                SysUserOnlineEntity online = new SysUserOnlineEntity();
                online.setSessionId(String.valueOf(session.getId()));
                online.setDeptName(session.getDeptName());
                online.setLoginName(session.getLoginName());
                online.setStartTimestamp(session.getStartTimestamp());
                online.setLastAccessTime(session.getLastAccessTime());
                online.setExpireTime(session.getTimeout());
                online.setIpaddr(session.getHost());
                online.setLoginLocation(AddressUtils.getRealAddressByIP(session.getHost()));
                online.setBrowser(session.getBrowser());
                online.setOs(session.getOs());
                online.setStatus(session.getStatus().getInfo());
                online.setSession(session);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

                Map<String,Object> map = new HashMap<>();
                map.put("sessionId",String.valueOf(session.getId()));
	            Long listByWhereCount = SpringUtils.getBean(SysUserOnlineService.class)
			            .findListByWhereCount(SysUserOnlineEntity.class, map);
	            map.put("deptName",String.valueOf(session.getDeptName()));
                map.put("loginName",String.valueOf(session.getLoginName()));
                map.put("startTimestamp",String.valueOf(df.format(session.getStartTimestamp())));
                map.put("lastAccessTime",String.valueOf(df.format(session.getLastAccessTime())));
                map.put("expireTime",String.valueOf(session.getTimeout()));
                map.put("ipaddr",String.valueOf(session.getHost()));
                map.put("loginLocation",String.valueOf(AddressUtils.getRealAddressByIP(session.getHost())));
                map.put("browser",String.valueOf(session.getBrowser()));
                map.put("os",String.valueOf(session.getOs()));
                map.put("status",String.valueOf(session.getStatus()));
               if(listByWhereCount==0){
	               SpringUtils.getBean(SysUserOnlineService.class).insert(SysUserOnlineEntity.class,map);
               }else {
	               SpringUtils.getBean(SysUserOnlineService.class).update(SysUserOnlineEntity.class,map);
               }


            }
        };
    }


    /**
     * 登陆信息
     * 
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args)
    {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = ShiroUtils.getIp();
        return new TimerTask()
        {
            @Override
            public void run()
            {
                StringBuilder s = new StringBuilder();
                s.append(ip);
                s.append(AddressUtils.getRealAddressByIP(ip));
                s.append(username);
                s.append(status);
                s.append(message);
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                Map<String,Object> loginInForMap = new HashMap<>();
                loginInForMap.put("loginName", username);
                loginInForMap.put("ipaddr", ip);
                loginInForMap.put("loginLocation", AddressUtils.getRealAddressByIP(ip));
                loginInForMap.put("browser", browser);
                loginInForMap.put("os", os);
                loginInForMap.put("msg", message);
                loginInForMap.put("loginTime",  DateUtils.getNowDate());
                // 插入数据
                SpringUtils.getBean(SysLoginInForService.class).insert(SysLoginInForEntity.class,loginInForMap);
            }
        };
    }
}
